package com.gk.javaservice.util.base;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;

public class FolderCopy {
	/**
	 * 文件夹复制
	 * 
	 * @param sourcePath
	 *            源文件夹目录
	 * @param newPath
	 *            新文件夹目录
	 * @throws Exception
	 */
	public static void copyDir(String sourcePath, String newPath) {
		// 初始化文件複製
		File file = new File(sourcePath);
		// 把文件夹里面路径放进数组
		String[] filePath = file.list();
		// 判断路劲是否存在，有不管，没有则创建
		if (!(new File(newPath)).exists()) {
			(new File(newPath)).mkdir();
		}
		for (int i = 0; i < filePath.length; i++) {
			if ((new File(sourcePath + file.separator + filePath[i]))
					.isDirectory()) {
				// 是文件夹
				copyDir(sourcePath + file.separator + filePath[i], newPath
						+ file.separator + filePath[i]);
			}
			if ((new File(sourcePath + file.separator + filePath[i])).isFile()) {
				try {
					copyFile(sourcePath + file.separator + filePath[i], newPath
							+ file.separator + filePath[i]);
				} catch (IOException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			}

		}
	}

	/**
	 * 文件具体复制方法
	 * 
	 * @param oldPath
	 * @param newPath
	 * @throws Exception
	 */
	private static void copyFile(String oldPath, String newPath)
			throws IOException {
		File oldFile = new File(oldPath);
		File file = new File(newPath);
		FileInputStream in = new FileInputStream(oldFile);
		FileOutputStream out = new FileOutputStream(file);
		byte[] buffer = new byte[2097152];
		int readByte = 0;
		while ((readByte = in.read(buffer)) != -1) {
			out.write(buffer, 0, readByte);
		}
		in.close();// 关闭流
		out.close();// 关闭流
	}
}
